package com.test38_集合;

import org.junit.Test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Demo05_MapEntry {

    /**
     * Iterator迭代输出Map
     */
    @Test
    public void test1() {
        {
            Map<String, String> map = new HashMap<>();
            map.put("YOOTK", "www.yootk.com");
            map.put("VIP", "yootk.ke.qq.com");
            Set<Map.Entry<String, String>> entrySet = map.entrySet();
            Iterator<Map.Entry<String, String>> iter = entrySet.iterator();
            while (iter.hasNext()) {
                Map.Entry<String, String> entry = iter.next();
                System.out.println("key = " + entry.getKey() + "、value = " + entry.getValue());
            }
        }
        {
            // JDK1.9支持
            Map.Entry<String, String> entry = Map.entry("YOOTK", "www.yootk.com");
            System.out.println(entry);
        }
    }

    /**
     * 通过foreach实现Map集合输出
     */
    @Test
    public void test2() {
        Map<String, String> map = new HashMap<>();
        map.put("YOOTK", "www.yootk.com");
        map.put("VIP", "yootk.ke.qq.com");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key = " + entry.getKey() + "、value = " + entry.getValue());
        }
    }

    /**
     * 通过keySet()遍历Map
     * 不推荐，效率低
     */
    @Test
    public void test3() {
        Map<String, String> map = new HashMap<>();
        map.put("YOOTK", "www.yootk.com");
        map.put("VIP", "yootk.ke.qq.com");
        Set<String> keys = map.keySet();    // 获取全部的key集合
        for (String key : keys) {
            System.out.println("key = " + key + "、value = " + map.get(key));
        }
    }

    /**
     * 自定义Map集合key
     * 如果哈希码的内容完全相同，那么在数据结构之中将其称为“哈希冲突”，
     * 面对“哈希冲突”在软件设计之中有四种解决方案：开放定址法、链地址法、建立公共溢出区、再哈希法。
     * Java是采用链地址法，这种操作的主要机制是将重复的Hash值的内容保存在一个链表之中。
     */
    @Test
    public void test4() {
        Map<Book5, String> map = new HashMap<>();
        map.put(new Book5("Java从入门到项目实战"), "Java小红书");
        map.put(new Book5("Python从入门到项目实战"), "Python小黄书");
        System.out.println(map.get(new Book5("Java从入门到项目实战")));
        System.out.println(map.get(new Book5("Python从入门到项目实战")));
    }
}

class Book5 {
    private String title;

    public Book5(String title) {
        this.title = title;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book5 book5 = (Book5) o;
        return title.equals(book5.title);
    }

    @Override
    public int hashCode() {
        // return Objects.hash(title);
        return 1;
    }
}
